import { useUserStore } from '@/store/modules/user'


function authPermission(permission: any) {
  try {
    const all_permission = "*:*:*"
    const userStore = useUserStore()

    if (!userStore || !userStore.permissions) {
      console.warn('UserStore or permissions not available')
      return false
    }

    const permissions = userStore.permissions

    if (!Array.isArray(permissions)) {
      console.warn('Permissions is not an array:', permissions)
      return false
    }

    if (permission && permission.length > 0) {
      return permissions.some((v: any) => {
        return all_permission === v || v === permission
      })
    } else {
      return false
    }
  } catch (error) {
    console.error('Error in authPermission:', error)
    return false
  }
}

function authRole(role: any) {
  try {
    const super_admin = "admin"
    const userStore = useUserStore()

    if (!userStore || !userStore.roles) {
      console.warn('UserStore or roles not available')
      return false
    }

    const roles = userStore.roles

    if (!Array.isArray(roles)) {
      console.warn('Roles is not an array:', roles)
      return false
    }

    if (role && role.length > 0) {
      return roles.some((v: any) => {
        return super_admin === v || v === role
      })
    } else {
      return false
    }
  } catch (error) {
    console.error('Error in authRole:', error)
    return false
  }
}

export default {
  // 验证用户是否具备某权限
  hasPermi(permission: any) {
    return authPermission(permission)
  },
  // 验证用户是否含有指定权限，只需包含其中一个
  hasPermiOr(permissions: any) {
    return permissions.some((item: string) => {
      return authPermission(item)
    })
  },
  // 验证用户是否含有指定权限，必须全部拥有
  hasPermiAnd(permissions: any) {
    return permissions.every((item: string) => {
      return authPermission(item)
    })
  },
  // 验证用户是否具备某角色
  hasRole(role: any) {
    return authRole(role)
  },
  // 验证用户是否含有指定角色，只需包含其中一个
  hasRoleOr(roles: any) {
    return roles.some((item: string) => {
      return authRole(item)
    })
  },
  // 验证用户是否含有指定角色，必须全部拥有
  hasRoleAnd(roles: any) {
    return roles.every((item: string) => {
      return authRole(item)
    })
  }
}
